#!/bin/bash

. /nyyos/remote/fastosc.sh
. /nyyos/remote/detectip.sh

show_help() {
    :
}

cmdopts=$(getopt --longoptions reboot:,check:,repair:,rebuild:,help \
                     --options +h -- "$@")
# set positional parameters
eval set -- "$cmdopts"

fip=
check=false
reboot=false
repair=false
rebuild=false

while true; do
  case "$1" in
    -h | --help )
        show_help
        exit ;;
    --repair )
        fip="$2"
        repair=true
        shift 2;;
    --rebuild )
        fip="$2"
        rebuild=true
        shift 2;;
    --check )
        fip="$2"
        check=true
        shift 2;;
    --reboot )
        fip="$2"
        reboot=true
        shift 2;;
    -- ) shift; break ;;
    * ) break ;;
  esac
done

trap cleanup EXIT

cleanup() {
    cleanup_osc
}

init_osc true $* || { . /nyyos/remote/baseosc.sh && init_osc || exit; }

#get_floatingIP $*
#exit

if [ -n "$fip" ]; then
    if [ "$fip" != "ALL" ]; then
        vmuuid=$(get_instance_by_fip $fip $*)
        [ -n "$vmuuid" ] || { echo "[ERROR] nova instance with $fip not found.(forget --project?)"; exit; }
        if $check || $repair || $rebuild ; then
            show_instance $vmuuid $*
            detect_fip $fip $vmuuid $* && { exit 0; }
        fi
        if $reboot || $repair; then
            reboot_instance $vmuuid $*
        elif $rebuild; then
            rebuild_instance $vmuuid $*
        fi
        exit $?
    fi
fi

# fip=ALL or fip is empty
if $repair; then
    action=reboot
elif $rebuild; then
    action=rebuild
else # detect all
    action=
fi

subprocs=()
i=-1
MAX=49
for x in $(get_floatingIP $*);do
         while [ ${#subprocs[@]} -eq $MAX ]; do
             sleep 0.5
             for y in $(seq 0 $i);do
                 p=${subprocs[$y]}
                 [ -n "$p" ] && { [ -z "$(ps -ho pid -p $p)" ] && unset subprocs[$y]; }
             done
         done
         ((i++))
         /bin/bash -c "\
. /nyyos/remote/fastosc.sh;\
. /nyyos/remote/detectip.sh;\
init_osc false || { . /nyyos/remote/baseosc.sh && init_osc || exit -1; };\
vmuuid=\$(get_instance_by_fip $x $*);\
detect_fip $x \$vmuuid $* && \
{ exit 0; }; \
if [ -n \"$action\" ]; then \
    vmuuid=\$(get_instance_by_fip $x $*); \
    if [ ! -n \"\$vmuuid\" ];then \
        echo \"[ERROR] nova instance with $x not found.(forget --project?)\";\
        exit;\
    fi;\
    ${action}_instance \$vmuuid $*; \
fi\
" &
         subprocs[$i]=$!
done
[ ${#subprocs[@]} -gt 0 ] && wait $(for x in ${subprocs[@]};do echo -n "$x ";done)

exit

